import axiosObj from "../../component/interceptor.js";
import alipay from "../../component/alipay.js";


// app.js
new Vue({
    el: '#app',
    data: {


        //我的账户
        currentTab: '1-1', // 默认显示我的账户内容
        tableData: [

        ],
        // 退款相关数据
        returnReasonDialogVisible: false,

        returnOrderId: null,
        trackingDialogVisible: false,
        trackingNumber: '',
        trackingOrderId: null,
          selectedReason: '',
                customReason: '',
                returnReason: '', // 退款理由


        //购物车
        cartData: [],// 购物车数据
        searchQuery: '', // 搜索关键字
        selectedItems: [], // 选中的商品
        showSubmitButton: false, // 控制是否显示提交订单按钮
        orderPopupVisible: false, // 控制订单弹窗显示
        newOrderData: [],//新订单数据
        newAdmitOrder: [],

        //我的订单

        //个人资料
        dialogVisible: false, // 控制编辑对话框显示
        editIndex: -1, // 保存编辑的地址索引
        editForm: { // 编辑表单数据
            name: '',
            phone: '',
            address: ''
        },
        addAddressDialogVisible: false, // 控制新增地址对话框显示
        addForm: { // 新增地址表单数据
            name: '',
            phone: '',
            address: ''
        },


        userData: {
            nickname: '', // 用户昵称
            userId: '', // 用户ID
            avatar: '', // 用户头像
            password: '', // 用户密码
            phone: '',//用户电话
            addresses: [ // 用户地址列表
                {
                    name: '', // 收件人姓名
                    phone: '', // 收件人电话
                    addressId: 0, // 地址ID
                    address: '', // 地址
                    addressIsDefault: 0,// 是否默认地址，0表示不是默认，1表示默认
                    userId: 0
                }
                // 其他地址...
            ]
        },


    },

    computed: {
    //我的订单
    sortedTableData() {
          const orderStatusPriority = {
            1: 1, // unpaid
            2: 2, // paid
            3: 3, // shipped
            5: 4  // received
          };

          // 使用slice()方法复制数组，以确保不修改原始数据
          const sortedData = this.tableData.slice().sort((a, b) => {
            return orderStatusPriority[a.status] - orderStatusPriority[b.status];
          });

          return sortedData;
        },

        //购物车
        filteredCartData() {
            if (!this.searchQuery) {
                return this.cartData;
            }
            const query = this.searchQuery.toLowerCase();
            return this.cartData.filter(item => item.name.toLowerCase().includes(query));
        },

        totalAmount() {
            let total = 0;
            this.selectedItems.forEach(item => {
                total += item.price * item.number;
            });

            return total;
        },
        totalRow() {
            return {
                selectedItemsLength: this.selectedItems.length,
                totalAmount: this.totalAmount,
                showSubmitButton: this.showSubmitButton,
            };
        },
        calculateTotalSum() {
            let totalSum = 0;
            this.myOrderData.forEach(item => {
                totalSum += item.price * item.count;
            });
            return totalSum;
        },
    },
    methods: {
        // 返回主页
        handleHome() {
            window.location.assign("/buyer/home")
        },
        handleLogout() {
            window.location.assign("/login")
        },
        //我的账户
        handleMenuSelect(index) {
            // 当菜单项被点击时触发，更新当前选中的标签页
            this.currentTab = index;
            if (index === '1-1') {
                this.getOrderList();
            }
            if (index === '1-2') {
                this.getCartData(); // 当点击个人资料时触发请求
            }
            if (index === '1-4') {
                this.getUserData(); // 当点击个人资料时触发请求
            }

        },
        toggleSelection(rows) {
            if (rows) {
                rows.forEach(row => {
                    this.$refs.multipleTable.toggleRowSelection(row);
                });
            } else {
                this.$refs.multipleTable.clearSelection();
            }
        },

        // 我的账户（订单列表）
        getOrderList() {
            axiosObj.get('/customer/order')
                .then(response => {
                    // 成功获取数据后更新订单数据
                    if (response.data.code === 1000) {

                        this.tableData = response.data.data;
                    } else {
                        console.error('获取订单数据失败:', response.data.msg);
                    }
                })
                .catch(error => {
                    console.error('获取订单数据失败:', error);
                });
        },

        payMyOrder(orderId) {
            const order = this.tableData.find(item => item.id === orderId);
            if (!order) {
                console.error('订单未找到:', orderId);
                return;
            }

            // 获取订单总价
            const priceAll = order.priceAll;
            orderId = [{
                orderId: orderId
            }]

            axiosObj.post('/customer/payOrder', orderId)
                .then(response => {
                    if (response.data.code === 1000) {
                        alert('支付成功！');
                        
                        this.getOrderList();
                    } else {
                        console.error('支付失败:', response.data.msg);
                    }
                })
                .catch(error => {
                    console.error('支付失败:', error);
                });

            alipay(orderId, priceAll)
            this.getOrderList()
        },

        // 收货订单
        receiveOrder(orderId) {
            axiosObj.post('/customer/receive', { orderId })
                .then(response => {
                    if (response.data.code === 1000) {
                        // 收货成功的处理逻辑，例如刷新页面或者提示用户收货成功
                        this.$message.success("receive success")
                        this.getOrderList()
                    } else {
                        console.error('收货失败:', response.data.msg);
                    }
                })
                .catch(error => {
                    console.error('收货失败:', error);
                });
        },
        //退款申请
        showReturnDialog(orderId) {
            this.returnOrderId = orderId;
            this.returnReasonDialogVisible = true;
        },
        //提交申请原因
        submitReturn() {
         if (this.selectedReason === 'Other') {
                        this.returnReason = this.customReason;
                    } else {
                        this.returnReason = this.selectedReason;
                    }

                    // 检查是否填写了退款理由
                    if (!this.returnReason) {
                        this.$message.error('Please enter a refund reason');
                        return;
                    }
            axiosObj.post('/customer/returnOrderSubmit', {
                orderId: this.returnOrderId,
                reason: this.returnReason

            }).then(response => {
                if (response.data.code === 1000) {
                    this.$message.success('Refund request submitted successfully');
                    this.returnReasonDialogVisible = false;
                    this.getOrderList(); // 刷新订单列表
                } else {
                    this.$message.error('Refund request submission failed: ' + response.data.msg);
                }
            }).catch(error => {
                console.error('退款申请提交失败:', error);
                this.$message.error('退款申请提交失败，请稍后重试');
            });
        },
        showTrackingDialog(orderId) {
            this.trackingOrderId = orderId;
            this.trackingDialogVisible = true;
        },
        //提交物流单号
        submitTrackingNumber() {
            axiosObj.post('/customer/returnOrderShip', {
                returnId: this.trackingOrderId,
                trackingNumber: this.trackingNumber
            }).then(response => {
                if (response.data.code === 1000) {
                    this.$message.success('物流单号提交成功');
                    this.trackingDialogVisible = false;
                    this.getOrderList(); // 刷新订单列表
                } else {
                    this.$message.error('物流单号提交失败: ' + response.data.msg);
                }
            }).catch(error => {
                console.error('物流单号提交失败:', error);
                this.$message.error('物流单号提交失败，请稍后重试');
            });
        },








        //购物车


        // 获取购物车数据的方法
        // goToShoppingCart() {
        //     // 点击购物车时触发的方法
        //     this.currentTab = '1-2'; // 假设 '1-2' 是购物车界面的标签页
        //     this.getCartData(); // 获取购物车数据
        // },
        getCartData() {
            axiosObj.get('/customer/getcart')
                .then(response => {
                    // 成功获取数据后更新购物车数据
                    if (response.data.code === 1000) {

                        this.cartData = response.data.data;
                    } else {
                        console.error('获取购物车数据失败:', response.data.msg);
                    }
                })
                .catch(error => {
                    console.error('获取购物车数据失败:', error);
                });
        },
        handleSelectionChange(val) {
            this.selectedItems = val;
            this.showSubmitButton = this.selectedItems.length > 0; // 当有选中商品时显示提交按钮
        },
        handleQuantityChange(row) {
            // 在这里可以处理数量变化后的逻辑，比如更新数据等
            console.log("Quantity changed:", row.number);
        },
        // 提交订单的方法


        submitOrder() {
            const newOrders = this.selectedItems.map(item => {
                // 计算订单总价
                const priceAll = item.number * item.price;

                return {
                    id: item.id,
                    name: item.name,
                    number: item.number,
                    price: item.price,
                    priceAll: priceAll,
                    orderTime: new Date().getTime()  // 假设订单时间为当前时间

                };
            });

            const productList = this.selectedItems.map(item => {
                return {
                    number: item.number,
                    productId: item.id
                };
            });

            // 发送 POST 请求
            axiosObj.post('/customer/admitOrder', productList)
                .then(response => {
                    if (response.data.code === 1000) {
                        // 处理成功提交订单的响应
                        // 更新 newOrderData
                        this.newOrderData = newOrders; // 合并新旧订单数据
                        this.newAdmitOrder = response.data.data;
                        this.showOrderPopup();
                        this.getCartData();
                    } else {
                        console.error('提交订单失败:', response.data.msg);
                    }
                })
                .catch(error => {
                    console.error('提交订单失败:', error);
                });
        },

        // 显示订单弹窗
        showOrderPopup() {
            this.orderPopupVisible = true;
        },

        // 关闭订单弹窗
        closeOrderPopup() {
            this.orderPopupVisible = false;
        },
        // 格式化时间
        formatDate(time) {
            const date = new Date(time);
            return date.toLocaleString();
        },
        payOrder() {
            // 支付订单
            if (this.newAdmitOrder.length === 0) {
                console.error('订单数据为空，无法支付！');
                return;
            }
            let priceAllOrder = 0
            const orderIdList = this.newAdmitOrder.map(item => {
                priceAllOrder += item.priceAll
                return {
                    orderId: item.id,
                }
            })

            axiosObj.post('/customer/payOrder', orderIdList)
                .then(response => {
                    if (response.data.code === 1000) {
                        this.$message({
                            showClose: true,
                            message: '付款成功',
                            type: 'success',
                            duration: 0
                        });
                        this.closeOrderPopup();
                        this.getCartData();
                    } else {
                        console.error('支付失败:', response.data.msg);
                    }
                })
                .catch(error => {
                    console.error('支付失败:', error);
                });

            alipay(orderIdList, priceAllOrder)
        },
        // 删除购物车商品
        removeItem(item) {
            // 构造请求数据
            const requestData = {
                shoppingBagList: [
                    {
                        buyerId: this.userData.userId,  // 假设你有用户ID
                        number: 0,  // 删除商品时，数量为0
                        productId: item.id
                    }
                ]
            };

            // 发送POST请求
            axiosObj.post('/customer/editNumber', requestData)
                .then(response => {
                    if (response.data.code === 1000) {
                        this.$message.success('删除成功');

                        // 更新购物车数据
                        this.getCartData();
                    } else {
                        this.$message.error('删除失败: ' + response.data.msg);
                    }
                })
                .catch(error => {
                    console.error('删除失败:', error);
                    this.$message.error('删除失败，请稍后重试');
                });
        },


        //我的订单


        //个人资料

        getUserData() {
            // 获取用户数据的方法
            axiosObj.get('/customer/address/getinfo')
                .then(response => {
                    if (response.data.code === 1000) {
                        const data = response.data.data;
                        this.userData.nickname = data.user.name;
                        this.userData.userId = data.user.id;
                        this.userData.phone = data.user.tel;
                        this.userData.avatar = data.user.avatar;
                        this.userData.password = data.user.password;

                        // 清空原有地址列表
                        this.userData.addresses = [];

                        // 填充新地址列表
                        data.destinationList.forEach(address => {//我们声明了一个变量 address
                            this.userData.addresses.push({
                                name: address.name,
                                phone: address.phone,
                                addressId: address.id,
                                address: address.address,
                                addressIsDefault: address.isDefault,
                                userId: address.userId
                            });
                        });

                    } else {
                        console.error('获取个人资料数据失败:', response.data.msg);
                    }
                })
                .catch(error => {
                    console.error('获取个人资料数据失败:', error);
                });
        },
        //保存个人信息
        saveUserInfo() {
            // 构造请求的数据
            const requestData = {
                avatar: this.userData.avatar,
                name: this.userData.nickname,
                password: this.userData.password,
                tel: this.userData.phone
            };

            axiosObj.post('/customer/address/editinfo', requestData)
                .then(response => {
                    if (response.data.code === 1000) {
                        console.log('用户信息保存成功:', response.data.msg);

                        this.$message.success('用户信息保存成功');
                    } else {
                        console.error('用户信息保存失败:', response.data.msg);

                        this.$message.error('用户信息保存失败: ' + response.data.msg);
                    }
                })
                .catch(error => {
                    console.error('用户信息保存失败:', error);

                    this.$message.error('用户信息保存失败，请稍后重试');
                });
        },

        // 修改默认地址
        setDefaultAddress(index) {
            // 设置为默认地址
            const destinationId = this.userData.addresses[index].addressId; // 获取地址的 ID
            axiosObj.post('/customer/address/changeDefault', null, {
                params: {
                    destination_id: destinationId
                }
            })
                .then(response => {
                    if (response.data.code === 1000) {
                        // 设置成功，更新对应地址的属性
                        this.userData.addresses.forEach((address, i) => {
                            if (i === index) {
                                address.addressIsDefault = 1; // 将当前地址设为默认地址
                            } else {
                                address.addressIsDefault = 0; // 其他地址设为非默认地址
                            }
                        });
                        // 禁用其他按钮
                        this.userData.addresses.forEach((address, i) => {
                            address.disabled = true;
                        });
                    } else {
                        console.error('设置默认地址失败:', response.data.msg);
                    }
                })
                .catch(error => {
                    console.error('设置默认地址失败:', error);
                });
        },


        //编辑地址
        editAddress(index) {
            this.editIndex = index;
            this.editForm = {...this.userData.addresses[index]};
            this.dialogVisible = true;
        },
        saveEdit() {
            // 将编辑后的数据保存到表格中
            this.$set(this.userData.addresses, this.editIndex, {...this.editForm});

            // 调用 POST 方法提交数据
            axiosObj.post('/customer/address/update', {
                address: this.editForm.address,
                id: this.editForm.addressId,
                name: this.editForm.name,
                phone: this.editForm.phone
            })
                .then(response => {
                    // 处理响应
                    console.log(response.data);
                    this.dialogVisible = false;
                })
                .catch(error => {
                    // 处理错误
                    console.error(error);
                });
        },
        //删除地址
        deleteAddress(index) {
            const destinationId = this.userData.addresses[index].addressId; // 获取地址的 ID
            axiosObj.post('/customer/address/delete', destinationId, {
                headers: {
                    'Content-Type': 'application/json'
                }
            })
                .then(response => {
                    if (response.data.code === 1000) {
                        // 删除本地 userData.addresses 中对应的地址

                        this.$message.success('地址删除成功。');
                        this.getUserData();
                    } else {
                        console.error('删除地址失败:', response.data.msg);
                        // 可选择显示删除失败的消息
                        this.$message.error('删除地址失败。');
                    }
                })
                .catch(error => {
                    console.error('删除地址失败:', error);
                    // 可选择显示删除失败的消息
                    this.$message.error('删除地址失败。');
                });
        },


        //新增地址

        addNewAddress() {
            // 将新增的地址数据保存到 userData.addresses 中
            this.userData.addresses.push({
                name: this.addForm.name,
                phone: this.addForm.phone,
                addressId: '', // 暂时为空
                address: this.addForm.address,
                addressIsDefault: '0' // 默认为非默认地址
            });

            // 调用 POST 方法提交新增的数据
            axiosObj.post('/customer/address/add', {
                address: this.addForm.address,
                name: this.addForm.name,
                phone: this.addForm.phone
            })
                .then(response => {
                    // 打印响应数据，查看后端返回的数据
                    console.log("Add Address Response:", response.data);
                    // 处理成功响应后调用 getUserData() 方法更新用户数据
                    this.getUserData();

                    // 处理响应
                    console.log(response.data);
                    this.addAddressDialogVisible = false; // 关闭对话框
                })
                .catch(error => {
                    // 处理错误
                    console.error(error);
                });

            // 清空表单数据
            this.addForm = {
                name: '',
                phone: '',
                address: ''
            };
        },


        handleAvatarChange(event) {
            // 处理头像上传
            const file = event.target.files[0];
            const reader = new FileReader();
            reader.onload = () => {
                this.userData.avatar = reader.result;
            };
            reader.readAsDataURL(file);
        },


    },
    mounted() {
        this.getOrderList()
        this.getUserData()
    }
})